package it.side.platform.client.ui;

import it.side.platform.client.module.Module;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.Frame;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class MainLayoutImpl extends Composite implements MainLayout {

	private static MainLayoutUiBinder uiBinder = GWT
			.create(MainLayoutUiBinder.class);

	interface MainLayoutUiBinder extends UiBinder<Widget, MainLayoutImpl> {
	}
	
	@UiField LayoutPanel modules;
	@UiField LayoutPanel content;
	List<ToggleButton> moduleButtons = new ArrayList<ToggleButton>();

	public MainLayoutImpl() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	@Override
	public void setModules(List<Module> modules) {
		VerticalPanel container = new VerticalPanel();
		final DeckPanel frames = new DeckPanel();
		for (Iterator<Module> iterator = modules.iterator(); iterator.hasNext();) {
			final Module module = iterator.next();
			final ToggleButton button = new ToggleButton(module.getName());
			frames.add(new Frame());
			button.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					if (button.isDown()) {
						for (Iterator<ToggleButton> iterator2 = moduleButtons.iterator(); iterator2.hasNext();) {
							ToggleButton tb = iterator2.next();
							if (tb!=button) {
								tb.setDown(false);
							} else {
								int index = moduleButtons.indexOf(tb);
								Frame frame = (Frame)frames.getWidget(index);
								if (frame.getUrl()==null || "".equals(frame.getUrl())) {
									frame.setUrl(module.getUrl());
								}
								frames.showWidget(index);
							}
						}
					}
				}
			});
			moduleButtons.add(button);
			container.add(button);
		}
		this.modules.add(container);
		this.content.add(frames);
	}
	
	
	
	
}
